package com.jz.community.modulemine.rechargephone.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.jakewharton.rxbinding2.view.RxView;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.enums.CodeType;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.permission.PermissionUtil;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.jz.community.modulemine.money.bean.MoneyInfoBean;
import com.jz.community.modulemine.rechargephone.adapter.PhoneMoneyAdapter;
import com.jz.community.modulemine.rechargephone.bean.PhoneFareBean;
import com.jz.community.modulemine.rechargephone.bean.PhonePriceBean;
import com.jz.community.modulemine.rechargephone.presenter.PhoneFarePresenter;
import com.jz.community.modulemine.rechargephone.ui.PhoneFareView;
import com.jz.community.modulemine.rechargephone.view.PhoneEditText;
import com.qmuiteam.qmui.util.QMUIKeyboardHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.shequren.communityPeople.pay.bean.PayEvent;
import cn.shequren.communityPeople.pay.constants.CommUnityPayConstants;
import cn.shequren.communityPeople.pay.utils.CommUnityPayUtil;
import io.reactivex.Observable;

@Route(path = RouterIntentConstant.RECHARGE_PHONE)
public class PhoneFareActivity extends BaseMvpActivity<PhoneFareView.View, PhoneFarePresenter> implements PhoneFareView.View {


    @BindView(R2.id.phone_fare_back)
    ImageView phoneFareBack;
    @BindView(R2.id.phone_fare_title)
    TextView phoneFareTitle;
    @BindView(R2.id.phone_fare_op)
    TextView phoneFareOp;
    @BindView(R2.id.phone_fare_toolbar)
    Toolbar phoneFareToolbar;
    @BindView(R2.id.phone_fare_edit)
    PhoneEditText phoneFareEdit;
    @BindView(R2.id.phone_fare_edit_delete)
    ImageView phoneFareEditDelete;
    @BindView(R2.id.phone_fare_address)
    ImageView phoneFareAddress;
    @BindView(R2.id.phone_fare_comm)
    TextView phoneFareComm;
    @BindView(R2.id.phone_fare_rv)
    RecyclerView phoneFareRv;
    @BindView(R2.id.recharge_ecard_icon)
    ImageView rechargeEcardIcon;
    @BindView(R2.id.recharge_ecard_money)
    TextView rechargeEcardMoney;
    @BindView(R2.id.recharge_ecard_choose)
    ImageView rechargeEcardChoose;
    @BindView(R2.id.recharge_ecard_rl)
    RelativeLayout rechargeEcardRl;
    @BindView(R2.id.recharge_wechat_icon)
    ImageView rechargeWechatIcon;
    @BindView(R2.id.recharge_wechat_choose)
    ImageView rechargeWechatChoose;
    @BindView(R2.id.recharge_wechat_rl)
    RelativeLayout rechargeWechatRl;
    @BindView(R2.id.recharge_alpay_icon)
    ImageView rechargeAlpayIcon;
    @BindView(R2.id.recharge_alipay_choose)
    ImageView rechargeAlipayChoose;
    @BindView(R2.id.recharge_alipay_rl)
    RelativeLayout rechargeAlipayRl;
    @BindView(R2.id.phone_fare_pay_ll)
    LinearLayout phoneFarePayLl;
    @BindView(R2.id.phone_fare_pay)
    TextView phoneFarePay;

    private List<PhonePriceBean.EmbeddedBean.ContentBean> phoneList = new ArrayList<>();
    private PhoneMoneyAdapter adapterPhone;
    private int page = 0;
    private int size = 10;

    private int oldPosition = -1;

    private int rechargeType = 0; // 1 微信 2支付宝 4 E卡

    private String sPhone = "";//充值号码
    private String sId;
    private String amt;
    private String money = "";
    private boolean isCanECard = true;

    private Observable<PayEvent> toPayRxBusObser;

    @Override
    protected int getContentView() {
        return R.layout.module_mine_activity_phone_fare;
    }

    @Override
    protected PhoneFarePresenter createPresenter() {
        return new PhoneFarePresenter(this);
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        setImmersionBar(phoneFareToolbar);
        phoneFareTitle.setText("手机充值");
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initDatas() {
        super.initDatas();

        SpannableString ss = new SpannableString("请输入手机号码");
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(16, true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        phoneFareEdit.setHint(new SpannedString(ss));

        phoneFareEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    phoneFareEditDelete.setVisibility(View.GONE);
                    if (oldPosition != -1) {
                        if (null != adapterPhone) {
                            adapterPhone.getData().get(oldPosition).setSelect(false);
                            adapterPhone.notifyDataSetChanged();
                        }

                    }
                    oldPosition = -1;
                    phoneFarePayLl.setVisibility(View.GONE);
                    phoneFarePay.setVisibility(View.GONE);
                    mPresenter.initPhoneData(page, size);
                } else {
                    phoneFareEditDelete.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 13) {
                    //走接口
                    phoneFarePayLl.setVisibility(View.VISIBLE);
                    phoneFarePay.setVisibility(View.VISIBLE);
                    mPresenter.initPhoneData(page, size);
                }

            }
        });

        GridLayoutManager layoutManager = new GridLayoutManager(mActivity, 3);
        phoneFareRv.setHasFixedSize(true);
        phoneFareRv.setFocusable(false);
        phoneFareRv.setLayoutManager(layoutManager);

        adapterPhone = new PhoneMoneyAdapter(R.layout.module_mine_item_phone_money, phoneList);
        phoneFareRv.setAdapter(adapterPhone);

        adapterPhone.setOnItemClickListener((adapter, view, position) -> {
            if (!RxDataTool.isNullString(phoneFareEdit.getPhoneText())) {
                if (phoneFareEdit.getPhoneText().length() == 11) {
                    if (position != oldPosition) {
                        if (oldPosition == -1) {
                            adapterPhone.getData().get(position).setSelect(true);
                        } else {
                            adapterPhone.change(oldPosition, position);
                        }

                        oldPosition = position;
                        adapterPhone.notifyDataSetChanged();
                        sId = adapterPhone.getData().get(position).getId();
                        amt = adapterPhone.getData().get(position).getOriginalPrice();
                        QMUIKeyboardHelper.hideKeyboard(phoneFareEdit);

                        if (!RxDataTool.isNullString(money)) {
                            if (RxDataTool.isNumber(money)) {
                                double mMoney = RxDataTool.stringToDouble(money);
                                double phonePrice = RxDataTool.stringToDouble(adapterPhone.getData().get(position).getSellingPrice());
                                if (mMoney > 0) {
                                    if (mMoney >= phonePrice) {
                                        rechargeEcardRl.setEnabled(true);
                                        isCanECard = true;
                                        if (rechargeType == 4) {
                                            rechargeEcardChoose.setImageResource(R.mipmap.choose_phone_yes);
                                        } else if (rechargeType == 0) {
                                            rechargeType = 4;
                                            rechargeEcardChoose.setImageResource(R.mipmap.choose_phone_yes);
                                        } else {
                                            rechargeEcardChoose.setImageResource(R.mipmap.choose_phone_no);
                                        }
                                    } else {
                                        rechargeEcardRl.setEnabled(false);
                                        isCanECard = false;
                                        rechargeEcardChoose.setImageResource(R.mipmap.choose_phone_limit);
                                        if (rechargeType == 4) {
                                            rechargeType = 0;
                                        }
                                    }
                                }
                            }
                        }

                    }
                }

            }

        });

        RxView.clicks(phoneFarePay)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    if (rechargeType != 0) {
                        sPhone = phoneFareEdit.getPhoneText();
                        if (!RxDataTool.isNullString(sPhone)) {
                            //电话号码不为空
                            if (!RxDataTool.isNullString(sId)) {
                                showPhoneFarePayPop(sPhone, amt, rechargeType);
                            } else {
                                showNormal("请选择充值金额");
                            }

                        }
                    } else {
                        showNormal("请选择支付方式");
                    }


                });

        paymentCallback();
        mPresenter.initMoneyData();
        mPresenter.initPhoneData(page, size);

    }


    /**
     * 话费充值确认弹框
     *
     * @param phone
     */
    private void showPhoneFarePayPop(String phone, String phoneMoney, int rechargeType) {
        String title = "将给手机" + phone + "充值" + phoneMoney + "元";
        new MaterialDialog.Builder(mActivity)
                .title(title)
                .titleColor(ContextCompat.getColor(this, R.color.balck))
                .content("支付成功后话费实时到账，请以运营商实际查询的信息为准。")
                .contentColor(ContextCompat.getColor(this, R.color.font_gary))
                .positiveText("确定")
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(this,R.color.negative_color))
                .positiveColor(ContextCompat.getColor(this,R.color.positive_color))
                .cancelable(false)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog dialog, DialogAction which) {
                        mPresenter.rechargePhone(phoneFareEdit.getPhoneText(), rechargeType, sId);
                        dialog.dismiss();
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog dialog, DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }

    @Override
    public void setPhoneData(PhonePriceBean entity) {
        phoneList = entity.get_embedded().getContent();

        if (null != phoneList && phoneList.size() > 0) {
            adapterPhone.setNewData(phoneList);
            adapterPhone.changeStatus(phoneFareEdit.getPhoneText());
        }

    }

    @Override
    public void phoneDataFail(String msg) {
        showNormal(msg);

    }

    @Override
    public void setMoneyData(MoneyInfoBean entity) {
        if (!Preconditions.isNullOrEmpty(entity) && !Preconditions.isNullOrEmpty(entity.getAmount())) {
            rechargeEcardMoney.setText("余额¥" + entity.getAmount());
            money = entity.getAmount();
        }

    }

    @Override
    public void MoneyDataFail(String msg) {
        rechargeEcardMoney.setText("");

    }

    @Override
    public void PhoneFareSuccess(PhoneFareBean entity) {
        if (rechargeType == 4) {
            //社区人E卡
            showNormal("充值成功");
            mPresenter.initMoneyData();
            startDealActivity();
        } else {
            if (!RxDataTool.isNullString(entity.getUserPaymentParams())) {
                if (rechargeType == 1) {
                    //微信充值
                    CommUnityPayUtil.goPay(mActivity, CommUnityPayConstants.REQUEST_CODE_SUCCESS, CommUnityPayConstants.PAY_METHOD_WECHAT, CommUnityPayConstants.PAY_MEDIUM_APP, entity.getUserPaymentParams());
                } else if (rechargeType == 2) {
                    //支付宝充值
                    CommUnityPayUtil.goPay(mActivity, CommUnityPayConstants.REQUEST_CODE_SUCCESS, CommUnityPayConstants.PAY_METHOD_ALIPAY_SDK, CommUnityPayConstants.PAY_MEDIUM_APP, entity.getUserPaymentParams());

                }
            }
        }

    }

    @Override
    public void PhoneFareFail(String msg) {
        showNormal("充值失败");

    }

    @SuppressLint("CheckResult")
    private void paymentCallback() {
        toPayRxBusObser = RxBus.getInstance().register(PayEvent.toPayRxBusTag, PayEvent.class);
        toPayRxBusObser.subscribe(payEvent -> {
            //支付成功回调
            int payResult = payEvent.getPayResult();
            if (payResult == CommUnityPayConstants.PAY_RESULT_SUCCESS) {
                handleToPayState(0);
            } else if (payResult == CommUnityPayConstants.PAY_RESULT_CANCEL) {
                handleToPayState(-1);
            } else if (payResult == CommUnityPayConstants.PAY_RESULT_ERROR) {
                handleToPayState(-2);
            }
        });
    }

    /**
     * 处理支付成功状态
     *
     * @param code
     */
    @SuppressLint("CheckResult")
    private void handleToPayState(int code) {
        if (code == CodeType.RECODE_1.getCodeType()) {
            //充值成功
            showNormal("充值成功");
            startDealActivity();
            RxBus.getInstance().unregister(PayEvent.toPayRxBusTag, toPayRxBusObser);
            finish();
        } else {
            //支付未成功
            showNormal(getResources().getString(R.string.fail_pay));
            RxBus.getInstance().unregister(PayEvent.toPayRxBusTag, toPayRxBusObser);
        }
    }

    /**
     * 检测申请权限
     */
    private void checkPermissions() {
        PermissionUtil.handleRunTimePermis(this, () -> {
            intentToContact();
        }, Manifest.permission.READ_CONTACTS);

    }

    private void intentToContact() {
        // 跳转到联系人界面
        Intent intent = new Intent();
        intent.setAction("android.intent.action.PICK");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setType("vnd.android.cursor.dir/phone_v2");
        startActivityForResult(intent, 0x30);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x30) {
            if (data != null) {
                Uri uri = data.getData();
                String phoneNum = null;
                String contactName = null;
                // 创建内容解析者
                ContentResolver contentResolver = getContentResolver();
                Cursor cursor = null;
                if (uri != null) {
                    cursor = contentResolver.query(uri,
                            new String[]{"display_name", "data1"}, null, null, null);
                }
                while (cursor.moveToNext()) {
                    contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    phoneNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                cursor.close();
                //  把电话号码中的  -  符号 替换成空格
                if (phoneNum != null) {
                    phoneNum = phoneNum.replaceAll("-", " ");
                    // 空格去掉  为什么不直接-替换成"" 因为测试的时候发现还是会有空格 只能这么处理
                    phoneNum = phoneNum.replaceAll(" ", "");
                }

//                editCustomerName.setText(contactName);
                phoneFareEdit.setText(phoneNum);
                if (!RxDataTool.isNullString(phoneNum)) {
                    phoneFareEdit.setSelection(phoneFareEdit.getText().toString().length());
                    phoneFarePayLl.setVisibility(View.VISIBLE);
                    phoneFarePay.setVisibility(View.VISIBLE);
                }
                mPresenter.initPhoneData(page, size);
            }
        }
    }

    private void startDealActivity() {
        Intent intent = new Intent(mActivity, FareDealActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getInstance().unregister(PayEvent.toPayRxBusTag, toPayRxBusObser);
    }

    @OnClick(R2.id.phone_fare_back)
    public void backClick(View view) {
        QMUIKeyboardHelper.hideKeyboard(phoneFareEdit);
        finish();
    }

    @OnClick(R2.id.phone_fare_op)
    public void dealClick(View view) {
        startDealActivity();
    }

    @OnClick(R2.id.phone_fare_edit_delete)
    public void deleteClick(View view) {
        phoneFareEdit.setText("");
    }

    @OnClick(R2.id.phone_fare_address)
    public void addressClick(View view) {
        checkPermissions();
    }

    @OnClick(R2.id.recharge_ecard_rl)
    public void eCardClick(View view) {
        //社区人E卡支付
        if (rechargeType != 4) {
            rechargeEcardChoose.setImageResource(R.mipmap.choose_phone_yes);
            rechargeWechatChoose.setImageResource(R.mipmap.choose_phone_no);
            rechargeAlipayChoose.setImageResource(R.mipmap.choose_phone_no);
            rechargeType = 4;
        }
    }

    @OnClick(R2.id.recharge_wechat_rl)
    public void weChatClick(View view) {
        //微信支付
        if (rechargeType != 1) {
            rechargeWechatChoose.setImageResource(R.mipmap.choose_phone_yes);
            rechargeAlipayChoose.setImageResource(R.mipmap.choose_phone_no);
            if (isCanECard) {
                rechargeEcardChoose.setImageResource(R.mipmap.choose_phone_no);
            } else {
                rechargeEcardChoose.setImageResource(R.mipmap.choose_phone_limit);
            }
            rechargeType = 1;
        }
    }

    @OnClick(R2.id.recharge_alipay_rl)
    public void aliPayClick(View view) {
        //支付宝支付
        if (rechargeType != 2) {
            rechargeAlipayChoose.setImageResource(R.mipmap.choose_phone_yes);
            rechargeWechatChoose.setImageResource(R.mipmap.choose_phone_no);
            if (isCanECard) {
                rechargeEcardChoose.setImageResource(R.mipmap.choose_phone_no);
            } else {
                rechargeEcardChoose.setImageResource(R.mipmap.choose_phone_limit);
            }
            rechargeType = 2;

        }
    }
}
